<?php
namespace control;
/*
*进项发票类
*/

class incomeInvoiceClass extends adIndexClass
{
    private const page = 'incomeInvoice';
    private const table = 'invoice_open';
    private const table_mx = 'invoice_open_detail';
    private const title = '进项发票';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'invoiceDate'          => [
                        'name'  => L('finance.table.kai_piao_ri_qi'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'classify'  => [
                        'name'  => L('finance.table.fpxz'),
                        'width' => 100,
                    ],
                    'state'         => [
                        'name'  => L('finance.table.fpzt'),
                        'width' => 100,
                    ],
                    'invoiceCode'          => [
                        'name'  => L('finance.table.fa_piao_dai_ma'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'invoiceNo'          => [
                        'name'  => L('finance.table.fa_piao_hao_ma'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'buyCompany'          => [
                        'name'  => L('finance.table.gou_huo_dan_wei'),
                        'width' => 200,
                    ],
                    'saleCompany'          => [
                        'name'  => L('finance.table.xhdw'),
                        'width' => 200,
                    ],
                    'money'          => [
                        'name'  => L('finance.table.jia_shui_he_ji').'（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'unTaxMoney'          => [
                        'name'  => L('finance.table.noTaxMoney').'（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'taxMoney'          => [
                        'name'  => L('finance.table.shui_e').'（' . static::$unit . '）',
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => L('finance.table.bei_zhu'),
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierInvoiceOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.fpxz') => select(array("name" => "invoiceType", 'option' => ['普票', '专票'])).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    L('finance.table.shi_you')   => text(array("name" => "text")),
                    L('finance.table.kai_piao_ri_qi') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function supplierInvoice(){
        $html = $this->supplierInvoiceOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }
    public function supplierInvoiceSearch(): bool|string
    {
        $supplierId= $this->post('targetId');
        //like查询数组
        $like = array(
            //编号
            "text" => $this->post('text'),//事由
        );
        //全等查询数组
        $equal = array(
            "invoiceType" => $this->post('invoiceType'),
            "type" => '收票',
            'coid' => self::$coid
        );
        $and = $this->seeSelf(self::page)." and khid = '$supplierId'";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'openDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'invoiceDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array("");
        //获取记录
        $url = root . "control/adIndex.html?cla=receiveInvoice";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "detail" => array("title" => L('finance.table.incomeInfo'), "click" => "newIframe('" . L('finance.table.incomeInfo') . "','" . $url . "&fun=home&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint']  . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('finance.table.fpxz') => select(array("name" => "invoiceType", 'option' => ['普票', '专票'])),
                    L('finance.table.gysmc')   => text(array("name" => "supplierName")),
                    L('finance.table.shi_you') => text(array("name" => "text")),
                ],
                [
                    L('finance.table.kai_piao_ri_qi') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=receiveInvoice";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('".L('finance.table.receiveInvoice')."','" . $url . "&fun=home')\" class='spanButton'>" . L('finance.table.handsInvoice') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>" . L('finance.table.export') . "</span></a>\n";
        }
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'冲红'})\" class='spanButton'>" . L('finance.table.red') . "</span>\n";
            $button .= "<span onclick=\"layer('{$this->get('cla')}','stateSwitch',{type:'作废'})\" class='spanButton'>" . L('finance.table.cancellation') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            //编号
            "text" => $this->post('text'),//事由
            "targetName" => $this->post('supplierName'),
        );
        //全等查询数组
        $equal = array(
            "invoiceType" => $this->post('invoiceType'),
            "type" => '收票',
            'coid' => self::$coid
        );
        $and = $this->seeSelf(self::page);
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'openDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'invoiceDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=receiveInvoice";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('finance.table.incomeInfo'), "click" => "newIframe('" . L('finance.table.incomeInfo') . "','" . $url . "&fun=home&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 启修改状态
     */
    public function stateSwitch()
    {
        $type = $this->post('type');
        $typeText = match ($type) {
            '冲红' => L('finance.table.chong_hong'),
            default => L('finance.table.zuo_fei'),
        };
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('finance.table.tip') . "：" => L('topic.table.changeTip') . "：" . $typeText,
            ),

        ), 'hidden' => hidden(array('name' => 'type', 'value' => $type))));
        //返回
        return $this->layer(array("title" => L('finance.table.ztqh'), "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     * 修改状态
     */
    public function stateSwitchEdit()
    {
        $idArr = $this->post('listId');
        $state = $this->post('type');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('finance.table.income_invoice_edit');
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = L('finance.table.qxzsj');
        } elseif (!in_array($state, ['冲红', '作废'])) {
            $json['warn'] = L('finance.table.lei_xing_cuo_wu');
        } else {
            $field = [
                'state' => $state,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $operate = match ($state) {
                    '冲红' => L('finance.table.chong_hong'),
                    default => L('finance.table.zuo_fei'),
                };
                $text = str_replace(['{{staffName}}', '{{state}}'], [$this->control['name'], $operate], L('finance.table.income_invoice_text')) . implode("','", $idArr);
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('finance.table.delIncomeInvoice');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                delete(array("table" => self::table_mx, "where" => " orderId = '$id' "));
                //返回
                $warn = L('finance.table.sccg');
                $x++;
                $text .= str_replace(['{{invoiceNo}}', '{{id}}'], [$info['invoiceNo'], $info['id']], L('finance.table.incomeInvoice_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.incomeInvoice_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.incomeInvoice_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = L('finance.table.nhmzdcdzx');
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = [L('finance.table.fa_piao_dai_ma'), L('finance.table.fpbh'), L('finance.table.fa_piao_ri_qi'), L('finance.table.fplx'), L('finance.table.isTax'), L('finance.table.ghdwmc'), L('finance.table.ghnsrsbh'), L('finance.table.ghdz、dh'), L('finance.table.ghkhxjzh'), L('finance.table.xhdwmc'), L('finance.table.xhnsrsbh'), L('finance.table.xhdz、dh'), L('finance.table.xhkhxjzh'),
                L('finance.table.shou_kuan_ren'), L('finance.table.fu_he_ren'), L('finance.table.kai_piao_ren'), L('finance.table.he_ji'), L('finance.table.shui_e'), L('finance.table.jia_shui_he_ji'), L('finance.table.bei_zhu'), L('finance.table.hwhyslwmc'), L('finance.table.gui_ge_xing_hao'), L('finance.table.dan_wei'), L('finance.table.shu_liang'), L('finance.table.dan_jia'), L('finance.table.jin_e'), L('finance.table.shui_lu'), L('finance.table.shui_e')];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $all = find(array('table' => 'invoice_open_detail', 'where' => "orderId = '$array[id]' order by list asc"));
                    foreach ($all['array'] as $item) {
                        $data[] = [$array['invoiceCode'], $array['invoiceNo'], $array['invoiceDate'], $array['classify'], $array['isTax'] ? '是' : '否', $array['buyCompany'],
                            $array['buyTaxNo'], $array['buyAddress'], $array['buyBank'], $array['saleCompany'],
                            $array['saleTaxNo'], $array['saleAddress'], $array['saleBank'], $array['receiveName'], $array['checkName'],
                            $array['createName'], $array['unTaxMoney'], $array['taxMoney'], $array['money'], $array['text'], $item['name'],
                            $item['model'], $item['unit'], $item['num'], currencyClass::intToDecimal($item['price'], $item['baseUnit']),
                            $item['money'], $item['tax'] * 100, $item['taxMoney']];
                    }
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.incomeInvoice_export_log'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, L('finance.table.incomeInvoice') . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = L('finance.table.nhmzbjdzx');
        }  else {
            $exampleData[] =[];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '发票代码'=>$example[0],
                            '发票编号'=>$example[1],
                            '发票日期'=>$example[2],
                            '发票类型'=>$example[3],
                            '是否含税'=>$example[4],
                            '购货单位名称'=>$example[5],
                            '购货纳税人识别号'=>$example[6],
                            '购货地址、电话'=>$example[7],
                            '购货开户行及账号'=>$example[8],
                            '销货单位名称'=>$example[9],
                            '销货纳税人识别号'=>$example[10],
                            '销货地址、电话'=>$example[11],
                            '销货开户行及账号'=>$example[12],
                            '收款人'=>$example[13],
                            '复核人'=>$example[14],
                            '开票人'=>$example[15],
                            '合计'=>$example[16],
                            '税额合计'=>$example[17],
                            '价税合计'=>$example[18],
                            '备注'=>$example[19],
                            '货物或应收劳务名称'=>$example[20],
                            '规格型号'=>$example[21],
                            '单位'=>$example[22],
                            '数量'=>$example[23],
                            '单价'=>$example[24],
                            '金额'=>$example[25],
                            '税率'=>$example[26],
                            '税额'=>$example[27],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.saleInvoice_export_template'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'import')) {
            $json['warn'] = L('finance.table.nhmzdrdzx');
        }else {
            $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = $i = 0;
            $text = '';
            $preInvoice = [];
            $this->startTrans();
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $line = str_replace(['{{i}}'], [$row_list], L('job.other.line'));
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    //主表
                    $invoice = query('invoice_open', "coid = '" . self::$coid . "' and invoiceCode = '$cell[发票代码]'");
                    if (empty($preInvoice) || $preInvoice['invoiceCode'] != $cell['发票编号']) {
                        if (isset($preInvoice['id']) && !empty($preInvoice['id'])) {
                            $total = find(array('table' => 'invoice_open_detail', 'single' => "orderId = '$preInvoice[id]'", 'field' => "ifnull(sum(taxMoney),0) as taxMoney,ifnull(sum(money),0) as money"));
                            $taxMoney = $total['taxMoney'];
                            //统计价税合计和税额
                            if ($preInvoice['isTax']) {
                                $withTaxMoney = $total['money'];
                            } else {
                                $withTaxMoney = $total['money'] + $taxMoney;
                            }
                            update(array('table' => 'invoice_open', 'field' => ['taxMoney' => $taxMoney, 'money' => $withTaxMoney, 'unTaxMoney' => $withTaxMoney - $taxMoney], 'where' => "id = '$preInvoice[id]'"));
                        }
                        $preInvoice = [];
                        $field = [
                            'id' => suiji(),
                            'stid' => self::$stid,
                            'state' => '正常',
                            'type' => '收票',
                            'coid' => self::$coid,
                            'classify' => $cell['发票类型'] ?: '普票',
                            'buyCompany' => $cell['购货单位名称'],
                            'buyTaxNo' => $cell['购货纳税人识别号'],
                            'buyAddress' => $cell['购货地址、电话'],
                            'buyBank' => $cell['购货开户行及账号'],
                            'checkName' => $cell['复核人'],
                            'receiveName' => $cell['收款人'],
                            'createName' => $cell['开票人'],
                            'invoiceDate' => $cell['发票日期'],
                            'invoiceCode' => $cell['发票代码'],
                            'invoiceNo' => $cell['发票编号'],
                            'isTax' => $cell['是否含税'] == '是' ? 1 : 0,
                            'saleCompany' => $cell['销货单位名称'],
                            'saleTaxNo' => $cell['销货纳税人识别号'],
                            'saleAddress' => $cell['销货地址、电话'],
                            'saleBank' => $cell['销货开户行及账号'],
                            'text' => $cell['备注'],
                        ];

                        $annotation = [
                            'invoiceDate' => L('finance.table.kai_piao_ri_qi'),
                            'invoiceCode' => L('finance.table.fa_piao_dai_ma'),
                            'invoiceNo' => L('finance.table.fpbh'),
                            'buyCompany' => L('finance.table.ghdwmc'),
                            'buyTaxNo' => L('finance.table.ghdwnsrsbh'),
                            'saleCompany' => L('finance.table.xhdw'),
                            'saleTaxNo' => L('finance.table.xhdwnsrsbh'),
                        ];
                        $rules = [
                            'invoiceDate' => 'required',
                            'invoiceCode' => 'required',
                            'invoiceNo' => 'required',
                            'buyCompany' => 'required',
                            'buyTaxNo' => 'required',
                            'saleCompany' => 'required',
                            'saleTaxNo' => 'required',
                        ];
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= $line . "：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                        } elseif (static::total(array('table' => self::table, 'where' => "coid = '" . self::$coid . "' and type = L('finance.table.openInvoice') and invoiceCode = '$field[invoiceCode]'")) > 0) {
                            $text .= $line . "：" . L('finance.table.yczcfp') . "<br>";
                        } else {
                            $warn = insert(["table" => self::table, "field" => $field]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $preInvoice = $field;
                                $text .= $line . "：" . L('job.other.import_success') . "<br>";
                            } else {
                                $text .= $line . "：" . L('job.other.import_failed') . "<br>";
                            }
                        }
                    }

                    if (isset($preInvoice['id']) && !empty($preInvoice['id'])) {
                        //明细
                        if (!empty($cell['货物或应收劳务名称'])) {
                            $text .= $line . "：" . L('finance.table.find_none_goods') . "<br>";
                        } elseif (empty($cell['金额']) || preg_match(checkPrice, $cell['金额']) == 0) {
                            $text .= $line . "：" . L('finance.table.find_none_money') . "<br>";
                        } else {
                            $baseUnit = currencyClass::calculateDecimal($cell['单价']);
                            $warn = static::insert(array(
                                'table' => 'invoice_open_detail',
                                'field' => [
                                    'id' => suiji(),
                                    'coid' => self::$coid,
                                    'orderId' => $preInvoice['id'],
                                    'name' => $cell['货物或应收劳务名称'],
                                    'model' => $cell['规格型号'],
                                    'unit' => $cell['单位'],
                                    'price' => $cell['单价'] * $baseUnit,
                                    'baseUnit' => $baseUnit,
                                    'num' => $cell['数量'],
                                    'money' => $cell['金额'],
                                    'tax' => $cell['税率'] / 100,
                                    'taxMoney' => $cell['税额'],
                                ],
                            ));
                            if ($warn == '新增成功') {
                                $x++;
                                $text .= $line . "：" . L('finance.table.saleInvoice_import_success') . "<br>";
                            } else {
                                $text .= $line . "：" . L('finance.table.saleInvoice_import_failed') . "<br>";
                            }
                        }
                    }
                    $preInvoice = $invoice;
                }
            }
            if ($i == $x && $x > 0) {
                $this->commitTrans();
            } else {
                $this->rollback();
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = str_replace(['{{staffName}}', '{{fileName}}'], [$this->control['name'], $_FILES['file']['name']], L('job.other.import_log')) . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'发票代码',
                    'aliasName'=>'发票代码',

                    'isMust'=>true,
                    'isRepeat'=>true,
                ],
                [
                    'columnName'=>'发票编号',
                    'aliasName'=>'发票编号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'发票日期',
                    'aliasName'=>'发票日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'发票类型',
                    'aliasName'=>'发票类型(普票/专票)',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'是否含税',
                    'aliasName'=>'是否含税(是/否)',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'购货单位名称',
                    'aliasName'=>'购货单位名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'购货纳税人识别号',
                    'aliasName'=>'购货纳税人识别号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'购货地址、电话',
                    'aliasName'=>'购货地址、电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'购货开户行及账号',
                    'aliasName'=>'购货开户行及账号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'销货单位名称',
                    'aliasName'=>'销货单位名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'销货纳税人识别号',
                    'aliasName'=>'销货纳税人识别号',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'销货地址、电话',
                    'aliasName'=>'销货地址、电话',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'销货开户行及账号',
                    'aliasName'=>'销货开户行及账号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'收款人',
                    'aliasName'=>'收款人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'复核人',
                    'aliasName'=>'复核人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'开票人',
                    'aliasName'=>'开票人',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'合计',
                    'aliasName'=>'合计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'税额合计',
                    'aliasName'=>'税额合计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'价税合计',
                    'aliasName'=>'价税合计',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'货物或应收劳务名称',
                    'aliasName'=>'货物或应收劳务名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'金额',
                    'aliasName'=>'金额',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'税率',
                    'aliasName'=>'税率%',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'税额',
                    'aliasName'=>'税额',

                    'isMust'=>false,
                ],
            ]
        };
    }
}
